/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */

package app.controllers.admin;

import app.Const;
import app.controllers.FileController;
import app.dtos.ImportMemberDTO;
import app.dtos.status.MemberStatus;
import app.kits.asyn.ImportMemberThread;
import app.models.DaoKit;
import app.models.member.Member;
import app.models.member.MemberRank;
import com.alibaba.fastjson.JSON;
import com.github.sog.config.StringPool;
import com.github.sog.controller.AjaxMessage;
import com.github.sog.controller.BasicController;
import com.github.sog.controller.datatables.core.DatatablesCriterias;
import com.github.sog.kit.date.DateProvider;
import com.github.sog.kit.encry.EncodeKit;
import com.github.sog.kit.servlet.RequestKit;
import com.github.sog.libs.AppFunc;
import com.github.sog.plugin.sqlinxml.SqlKit;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.upload.UploadFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 会员管理.
 * </p>
 *
 * @author sagyf yang
 * @version 1.0 2014-04-19 10:16
 * @since JDK 1.6
 */
public class MemberController extends BasicController {

    public static final  String FORM_ATTR = "member";
    private static final Logger logger    = LoggerFactory.getLogger(MemberController.class);

    /**
     * The index route.
     */
    public void index() {
        render("index.ftl");
    }


    public void list() {
        final DatatablesCriterias criterias = getCriterias();
        Page<Member> memberPage = Member.dao.datatable(criterias);

        renderDataTables(memberPage, criterias);
    }


    public void create() {

        Member member = new Member();
        member.set("gender", false);
        setAttr(FORM_ATTR, member);
        setAttr("ranks", MemberRank.dao.all());
        setAttr(Const.ACTION_ATTR, Const.CREATE_ACTION);
        render("item.ftl");
    }

    public void edit() {

        final long id = getParaToLong(0, 0l);
        if (id > 0) {
            Member member = Member.dao.findById(id);

            setAttr(FORM_ATTR, member);
            setAttr("ranks", MemberRank.dao.all());
            setAttr(Const.ACTION_ATTR, Const.CREATE_ACTION);
            render("item.ftl");
        } else {
            redirect("/admin/member");
        }
    }

    public void remove() {
        String remove_ids = getPara(Const.DATA_PARAM);
        List<String> ids = AppFunc.COMMA_SPLITTER.splitToList(remove_ids);
        List<Member> update_members = Lists.newArrayList();
        for (String id : ids) {
            Member _member = new Member();
            _member.set(Const.COLUMN_STATUS, MemberStatus.REMOVE);
            _member.set(AppFunc.TABLE_PK_COLUMN, id);
            update_members.add(_member);
        }
        if (DaoKit.batch_update(SqlKit.sql("member.changeStatus"), update_members)) {
            renderSuccess();
        } else {
            renderError("删除出现错误");
        }
    }


    public void save() {
        Member member = getModel(Member.class);
        if (DaoKit.isNew(member)) {
            member.set(Const.COLUMN_STATUS, MemberStatus.OFFICIAL);
            member.set("update_time", DateProvider.DEFAULT.getCurrentDate());
            member.save();
        } else {
            member.set("update_time", DateProvider.DEFAULT.getCurrentDate());
            member.update();
        }
        redirect("/admin/member");
    }


    public void leadin() {
        final HttpServletRequest request = getRequest();
        final HttpServletResponse response = getResponse();
        RequestKit.deleteCookie(request, response, Const.COOKIE_IMPORT_FILE, true);

        final UploadFile excelfile = this.getFile();
        if (excelfile != null) {
            final String extension = FilenameUtils.getExtension(excelfile.getOriginalFileName());
            if (StringUtils.equals("xls", extension)
                    || StringUtils.equals("xlsx", extension)
                    || StringUtils.equals("tsv", extension)) {

                final String file_name = EncodeKit.toUUID() + StringPool.DOT + extension;
                try {
                    final String import_tmp_dir = PathKit.getWebRootPath() + File.separator + FileController.uploadroot + File.separator + "import";
                    final String pathname = import_tmp_dir + File.separator + file_name;
                    final File to = new File(pathname);
                    Files.createParentDirs(to);
                    Files.copy(excelfile.getFile(), to);
                } catch (IOException e) {
                    logger.error("upload file is error!", e);
                }
                RequestKit.setCookie(request, response, Const.COOKIE_IMPORT_FILE, file_name, Const.IMPORT_MAX_AGE);
                renderText(JSON.toJSONString(AjaxMessage.ok()));
//                EventBusContext.post(new ImportEDto(excelfile.getFile(), extension));
            } else {
                renderText(JSON.toJSONString(AjaxMessage.error("请上传Excel文件或者tsv文件")));

                FileUtils.deleteQuietly(excelfile.getFile());
                return;
            }
        } else {

            renderText(JSON.toJSONString(AjaxMessage.error("请上传文件")));
            return;
        }

        renderText(JSON.toJSONString(AjaxMessage.ok()));
    }

    public void start_import() {
        final String import_file_name = getCookie(Const.COOKIE_IMPORT_FILE);
        if (Strings.isNullOrEmpty(import_file_name)) {
            renderJson(AjaxMessage.nodata());
        } else {
            final String import_tmp_dir = PathKit.getWebRootPath() + File.separator + FileController.uploadroot + File.separator + "import";
            final String pathname = import_tmp_dir + File.separator + import_file_name;
            int status = ImportMemberThread.getInstace().start(new File(pathname));
            switch (status) {
                case -1:
                    renderJson(AjaxMessage.failure("超出同时导入文件数量，无法导入"));
                    break;
                case 0:
                    renderJson(AjaxMessage.failure("文件已经在导入了!"));
                    break;
                case 1:
                    renderSuccess();
                    break;
                default:
            }
        }
    }

    public void stop_import() {
        final String import_file_name = getCookie(Const.COOKIE_IMPORT_FILE);
        if (Strings.isNullOrEmpty(import_file_name)) {
            renderJson(AjaxMessage.nodata());
        } else {
            final String import_tmp_dir = PathKit.getWebRootPath() + File.separator + FileController.uploadroot + File.separator + "import";
            final String pathname = import_tmp_dir + File.separator + import_file_name;
            ImportMemberThread.getInstace().stop(new File(pathname));
        }
    }

    public void import_status() {
        final String import_file_name = getCookie(Const.COOKIE_IMPORT_FILE);
        if (Strings.isNullOrEmpty(import_file_name)) {
            renderJson(AjaxMessage.failure("文件参数不能为空"));
        } else {

            final String import_tmp_dir = PathKit.getWebRootPath() + File.separator + FileController.uploadroot + File.separator + "import";
            final String pathname = import_tmp_dir + File.separator + import_file_name;
            if (new File(pathname).exists()) {
                final String cacheName = Const.CACHE_IMPORT_MASK + StringPool.DOLLAR + import_file_name;
                final List cacheKeys = CacheKit.getKeys(cacheName);
                if (cacheKeys != null && !cacheKeys.isEmpty()) {
                    List<ImportMemberDTO> importMemberDTOs = Lists.newArrayList();
                    for (Object cacheKey : cacheKeys) {
                        ImportMemberDTO memberDTO = CacheKit.get(cacheName, cacheKey);
                        importMemberDTOs.add(memberDTO);
                        CacheKit.remove(cacheName, cacheKey);
                    }
                    renderJson(AjaxMessage.nodata(importMemberDTOs));
                } else {
                    renderJson(AjaxMessage.nodata());
                }
            } else {
                renderJson(AjaxMessage.ok());
            }

        }
    }
}